package com.scsj.supermarket.view.fragment.fivepagemodel;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.ShopCartAdapter;
import com.scsj.supermarket.base.ShopCarBase;
import com.scsj.supermarket.bean.BaseBean;
import com.scsj.supermarket.bean.ShopCarBean;
import com.scsj.supermarket.bean.ShopCartBean;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.ShopCarPresenter;
import com.scsj.supermarket.utils.DialogUtils;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.utils.ToastMiddleUtils;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 购物车页面
 */

public class ShoppingFragment extends BaseFragment implements View.OnClickListener, ShopCarBase.IView {

    private TextView carr_edit;//顶部导航栏 编辑
    private LinearLayout status_buy, status_edit;//底部栏 购买状态，编辑状态
    private Boolean isuyBuy = true;//是否是购物状态
    private LinearLayout card_buy;//去结算
    private TextView cart_share, cart_follow, cart_delete;//分享、移入关注、删除
    private LinearLayout shopcart_addselect_ll;
    private ImageView shopcart_addselect_iv;
    private TextView tvShopCartSubmit, tvShopCartSelect, tvShopCartTotalNum;
    private View mEmtryView;
    private RecyclerView rlvShopCart, rlvHotProducts;
    private ShopCartAdapter mShopCartAdapter;
    private LinearLayout llPay;
    private LinearLayout rlHaveProduct;
    private List<ShopCartBean.CartlistBean> mAllOrderList = new ArrayList<>();
    private ArrayList<ShopCartBean.CartlistBean> mGoPayList = new ArrayList<>();
    private TextView tvShopCartTotalPrice;
    private int mCount, mPosition;
    private float mTotalPrice1;
    private boolean mSelect;
    private ShopCarPresenter presenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_forth, null);

        presenter = new ShopCarPresenter(this);
        presenter.deliverAllList();

        initView(view, null);
        initMove();
        getBus();
        initListener();

        return view;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        carr_edit = view.findViewById(R.id.carr_edit);
        status_buy = view.findViewById(R.id.status_buy);
        status_edit = view.findViewById(R.id.status_edit);

        if (isuyBuy) {
            carr_edit.setText("编辑");
            status_buy.setVisibility(View.VISIBLE);
            status_edit.setVisibility(View.GONE);
        } else {
            carr_edit.setText("完成");
            status_buy.setVisibility(View.GONE);
            status_edit.setVisibility(View.VISIBLE);
        }

        card_buy = view.findViewById(R.id.card_buy);
        cart_share = view.findViewById(R.id.cart_share);
        cart_follow = view.findViewById(R.id.cart_follow);
        cart_delete = view.findViewById(R.id.cart_delete);

        shopcart_addselect_ll = view.findViewById(R.id.shopcart_addselect_ll);
        shopcart_addselect_iv = view.findViewById(R.id.shopcart_addselect_iv);
        tvShopCartSelect = (TextView) view.findViewById(R.id.tv_shopcart_addselect);
        tvShopCartTotalPrice = (TextView) view.findViewById(R.id.tv_shopcart_totalprice);
        tvShopCartTotalNum = (TextView) view.findViewById(R.id.tv_shopcart_totalnum);

        rlvShopCart = (RecyclerView) view.findViewById(R.id.rlv_shopcart);
        llPay = (LinearLayout) view.findViewById(R.id.ll_pay);
        tvShopCartSubmit = (TextView) view.findViewById(R.id.tv_shopcart_submit);
    }

    @Override
    protected void initListener() {
        carr_edit.setOnClickListener(this);
        card_buy.setOnClickListener(this);
        cart_share.setOnClickListener(this);
        cart_follow.setOnClickListener(this);
        cart_delete.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return 0;
    }


    public void initMove() {

        rlvShopCart.setLayoutManager(new LinearLayoutManager(getHoldingActivity()));
        rlvShopCart.setNestedScrollingEnabled(false);
        mShopCartAdapter = new ShopCartAdapter(getHoldingActivity(), mAllOrderList);
        rlvShopCart.setAdapter(mShopCartAdapter);

        //删除商品接口
        mShopCartAdapter.setOnDeleteClickListener(new ShopCartAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(View view, int position, String cartid) {

                mShopCartAdapter.notifyDataSetChanged();

            }
        });

        //修改数量接口
        mShopCartAdapter.setOnEditClickListener(new ShopCartAdapter.OnEditClickListener() {
            @Override
            public void onEditClick(int position, String cartid, int count) {
                mCount = count;
                mPosition = position;
            }
        });

        //实时监控全选按钮
        mShopCartAdapter.setResfreshListener(new ShopCartAdapter.OnResfreshListener() {
            @Override
            public void onResfresh(boolean isSelect) {
                mSelect = isSelect;
                if (isSelect) {
                    shopcart_addselect_iv.setImageResource(R.mipmap.cart_selected);
                } else {
                    shopcart_addselect_iv.setImageResource(R.mipmap.cart_unselected);
                }
                float mTotalPrice = 0;
                int mTotalNum = 0;
                mTotalPrice1 = 0;
                mGoPayList.clear();
                for (int i = 0; i < mAllOrderList.size(); i++)
                    if (mAllOrderList.get(i).getIsSelect()) {
                        mTotalPrice += Float.parseFloat(mAllOrderList.get(i).getPrice()) * mAllOrderList.get(i).getCount();
                        mTotalNum += 1;
                        mGoPayList.add(mAllOrderList.get(i));
                    }
                mTotalPrice1 = mTotalPrice;
                tvShopCartTotalPrice.setText("合计：" + mTotalPrice);
                tvShopCartTotalNum.setText("" + mTotalNum);
            }
        });

        //全选
        shopcart_addselect_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelect = !mSelect;
                if (mSelect) {
                    shopcart_addselect_iv.setImageResource(R.mipmap.cart_selected);
                    for (int i = 0; i < mAllOrderList.size(); i++) {
                        mAllOrderList.get(i).setSelect(true);
                        mAllOrderList.get(i).setShopSelect(true);
                    }
                } else {
                    shopcart_addselect_iv.setImageResource(R.mipmap.cart_unselected);
                    for (int i = 0; i < mAllOrderList.size(); i++) {
                        mAllOrderList.get(i).setSelect(false);
                        mAllOrderList.get(i).setShopSelect(false);
                    }
                }
                mShopCartAdapter.notifyDataSetChanged();
            }
        });
        initData();
        mShopCartAdapter.notifyDataSetChanged();
    }

    public static void isSelectFirst(List<ShopCartBean.CartlistBean> list) {
        if (list.size() > 0) {
            list.get(0).setIsFirst(1);
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i).getShopId() == list.get(i - 1).getShopId()) {
                    list.get(i).setIsFirst(2);
                } else {
                    list.get(i).setIsFirst(1);
                }
            }
        }
    }

    public void getBus() {

        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent user) {
                        if (user.getCode().equals("SHOPPING")) {
                            isSelectFirst(user.getData());
                        }
                    }
                });

    }

    private void share() {

        DialogUtils.getInstance()
                .with(getHoldingActivity())//上下文
                .setlayoutId(R.layout.make_money_pop_window_layout)//布局文件
                .setlayoutPosition(Gravity.BOTTOM)//位置
                .setlayoutAnimaType(0)//动画类型:0自下而上动画，1淡入淡出动画
                .setlayoutPading(20, 0, 20, 20)//与屏幕距离
                .setOnChildViewclickListener(new DialogUtils.ViewInterface() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                        //处理dialog内部控件的点击事件
                        LinearLayout weichat_share_ll = view.findViewById(R.id.weichat_share_ll);
                        weichat_share_ll.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToastMiddleUtils.ToastMiddle(getHoldingActivity(), "微信");
                            }
                        });
                        TextView disMissTv = view.findViewById(R.id.share_dismiss_tv);
                        disMissTv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                DialogUtils.dismiss();
                            }
                        });
                    }
                })
                .show();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.carr_edit://顶部导航栏 编辑
                isuyBuy = !isuyBuy;
                if (isuyBuy) {
                    carr_edit.setText("编辑");
                    status_buy.setVisibility(View.VISIBLE);
                    status_edit.setVisibility(View.GONE);
                } else {
                    carr_edit.setText("完成");
                    status_buy.setVisibility(View.GONE);
                    status_edit.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.card_buy://去结算
                if (Integer.parseInt(tvShopCartTotalNum.getText().toString()) > 0) {
                    SkipUtils.toSubmitOrderPage(getHoldingActivity());
                } else {
                    Toasty.info(getHoldingActivity(), "您还没有选择商品哦").show();
                }
                break;
            case R.id.cart_share://分享
                if (Integer.parseInt(tvShopCartTotalNum.getText().toString()) > 0) {
                    share();
                } else {
                    Toasty.info(getHoldingActivity(), "您还没有选择商品哦").show();
                }
                break;
            case R.id.cart_follow://移入关注
                if (Integer.parseInt(tvShopCartTotalNum.getText().toString()) > 0) {
                    actionSheetDialog("当前选中" + tvShopCartTotalNum.getText().toString() + "种商品，关注成功后将从购物车删除，确认关注？");
                } else {
                    Toasty.info(getHoldingActivity(), "您还没有选择商品哦").show();
                }
                break;
            case R.id.cart_delete://删除
                if (Integer.parseInt(tvShopCartTotalNum.getText().toString()) > 0) {
                    actionSheetDialog("确认要删除这" + tvShopCartTotalNum.getText().toString() + "种商品么？");
                } else {
                    Toasty.info(getHoldingActivity(), "您还没有选择商品哦").show();
                }
                break;

            default:
                break;
        }
    }

    private void actionSheetDialog(String title) {
        final String[] stringItems = {"确认"};
        final ActionSheetDialog dialog = new ActionSheetDialog(getHoldingActivity(), stringItems, null);
        dialog.title(title).titleTextColor(getHoldingActivity().getResources().getColor(R.color.default_text_color)).titleTextSize_SP(10)//
                .show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {

                ArrayList<String>delIdList = new ArrayList<>();
                for (int i = 0;i<mAllOrderList.size();i++){
                    if (mAllOrderList.get(i).getIsSelect()){
                        delIdList.add(mAllOrderList.get(i).getId());
                        mAllOrderList.remove(i);
                        mShopCartAdapter.notifyItemRemoved(i);
                        mShopCartAdapter.notifyItemChanged(i,mAllOrderList.size());
                    }
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("shopCartIdList",delIdList);
                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());
                presenter.deliverShopCarDel(body);

                dialog.dismiss();
            }
        });
    }

    @Override
    public void showSuccessMsg(String s) {
        Toasty.info(getHoldingActivity(), s).show();
    }

    @Override
    public void showErrorMsg(String s) {
        Toasty.info(getHoldingActivity(), s).show();
    }

    @Override
    public void setAllData(ShopCarBean shopCarBean) {

        int size = shopCarBean.getData().size();
        for (int i = 0; i < size; i++) {
            int goodSize = shopCarBean.getData().get(i).getAppFindGoodsByShopCartVoList().size();
            for (int j = 0; j < goodSize; j++) {
                ShopCartBean.CartlistBean sb = new ShopCartBean.CartlistBean();
                sb.setShopId(shopCarBean.getData().get(i).getStore().getId());
                //String.valueOf(shopCarBean.getData().get(i).getAppFindGoodsByShopCartVoList().get(j).getGoods().getGoodsPromotionPrice())
                sb.setPrice("888");
                //String.valueOf(shopCarBean.getData().get(i).getAppFindGoodsByShopCartVoList().get(j).getGoods().getGoodsPromotionPrice())
                sb.setOldprice("666");
                sb.setDefaultPic(shopCarBean.getData().get(i).getResourceLogoInfo().getUrl());
                sb.setProductName(shopCarBean.getData().get(i).getAppFindGoodsByShopCartVoList().get(j).getGoods().getGoodsName());
                sb.setShopName(shopCarBean.getData().get(i).getStore().getName());
                sb.setCount(shopCarBean.getData().get(i).getAppFindGoodsByShopCartVoList().get(j).getBuyNum());
                mAllOrderList.add(sb);
            }
        }
         isSelectFirst(mAllOrderList);
    }

    @Override
    public void setShopCarDel(BaseBean baseBean) {

    }

    @Override
    public void setShopCarSendFare(BaseBean baseBean) {

    }
}
